package com.smitish.vueblog.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smitish.vueblog.common.lang.Result;
import com.smitish.vueblog.entity.Blog;
import com.smitish.vueblog.entity.Collection;
import com.smitish.vueblog.entity.Logs;
import com.smitish.vueblog.service.BlogService;
import com.smitish.vueblog.service.CollectionService;
import com.smitish.vueblog.service.LogsService;
import com.smitish.vueblog.util.ShiroUtil;
import com.smitish.vueblog.vo.CollectionBlogVO;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Smitish
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {

    @Autowired
    CollectionService collectionService;

    @Autowired
    LogsService logsService;

    @Autowired
    BlogService blogService;

    /**
     * 通过用户ID 查询其的喜欢
     *
     * @param id          用户ID
     * @param currentPage 当前页码
     * @param type        1-收藏，2-喜欢
     * @return 返回喜欢文字的数量 和结果集
     */
    @GetMapping("/getMyLikes/{id}")
    public Result getPost(@PathVariable(name = "id") Long id,
                          @RequestParam(defaultValue = "1") Integer currentPage,
                          @RequestParam(defaultValue = "1") Long type) {
        if (type == 1) {
            Page<CollectionBlogVO> page1 = collectionService.getCollectionBlog(new Page<>(currentPage, 12), id, type);
            if (page1.getTotal() == 0) {
                return Result.succ(200, "您还没有收藏任何文章“", null);
            }
            return Result.succ(200, "查询成功", page1);
        } else {
            Page<CollectionBlogVO> page1 = collectionService.getCollectionBlog(new Page<>(currentPage, 5), id, type);
            if (page1.getTotal() == 0) {
                return Result.succ(200, "您还没有点赞任何文章", null);
            }
            return Result.success(page1);
        }
    }

    /**
     * 点赞或收藏 取消点赞或取消收藏操作
     *
     * @param collection 收藏和点赞的实体类
     * @return 返回操作结果
     */
    @RequiresAuthentication
    @PostMapping("/star")
    public Result star(@Validated @RequestBody Collection collection) {
        // 防止用户 post恶意修改不是自己信息的文章
        Assert.isTrue(ShiroUtil.getProfile().getId().longValue() == collection.getUserId().longValue(), "没有权限编辑");
        // 收藏
        if (collection.getType() == 1) {
            // 1. 判断是否收藏了
            // 用户ID
            Long userId = collection.getUserId();
            // 文章ID
            Long postId = collection.getPostId();
            Collection user = collectionService.getOne(new QueryWrapper<Collection>()
                    .eq("user_id", userId)
                    .eq("post_id", postId)
                    .eq("type", 1));
            // 2. 收藏就取消收藏，未收藏就收藏
            // 3. 返回结果
            return getResult(collection, user);
        } else {
            // 1. 判断是否收藏了
            // 用户ID
            Long userId = collection.getUserId();
            // 文章ID
            Long postId = collection.getPostId();
            Collection user = collectionService.getOne(new QueryWrapper<Collection>()
                    .eq("user_id", userId)
                    .eq("post_id", postId)
                    .eq("type", 2));
            // 2. 收藏就取消收藏，未收藏就收藏
            // 3. 返回结果
            return getResult(collection, user);
        }
    }


    /**
     * 点赞或收藏 取消点赞或取消收藏操作 需要用的函数
     *
     * @param collection 收藏和点赞的实体类
     * @param user       查询出来的Collection实体类
     * @return 返回结果集给/collection/star接口
     */
    @RequiresAuthentication
    private Result getResult(@RequestBody @Validated Collection collection, Collection user) {
        // 新建logs对象
        Logs logs = new Logs();
        // user 用于判断是 取消点赞或取消收藏 还是 点赞或收藏
        if (user != null) {
            // 从m_collection表中移除数据
            boolean b = collectionService.removeById(user.getId());
            if (b) {
                // 从表m_blog中获取blog数据
                Blog blogServiceById = blogService.getById(collection.getPostId());
                // 给Logs实体类的对象logs赋值
                logs.setUserId(ShiroUtil.getProfile().getId());
                // type为1是收藏
                if (collection.getType() == 1)
                    logs.setLogContent("取消收藏了“\"" + blogServiceById.getTitle() + "\"");
                else
                    logs.setLogContent("取消点赞了“\"" + blogServiceById.getTitle() + "\"");
                // 上传用户logs信息
                logsService.saveOrUpdate(logs);
                return Result.succ(200, "取消成功", null);
            }
            return Result.fail("取消失败");
        } else {
            System.out.println(collection);
            // 直接将collection对象上传到数据库
            boolean save = collectionService.save(collection);
            if (save) {
                Blog blogServiceById = blogService.getById(collection.getPostId());
                logs.setUserId(ShiroUtil.getProfile().getId());
                if (collection.getType() == 1)
                    logs.setLogContent("收藏了“\"" + blogServiceById.getTitle() + "\"");
                else
                    logs.setLogContent("点赞了“\"" + blogServiceById.getTitle() + "\"");
                logsService.saveOrUpdate(logs);
                return Result.succ(200, "成功", null);
            }
            return Result.fail("失败");
        }
    }

    /**
     * 获取文章有多少点赞 和多少收藏函数
     *
     * @param id 文章id
     * @return 返回HashMap做为Json结果集
     */
    @GetMapping("/getPost/{id}")
    public Map<String, Object> getPost(@PathVariable(name = "id") Long id) {
        HashMap<String, Object> map = new HashMap<>();
        // 1.添加喜欢个数
        int collection = collectionService.count(new QueryWrapper<Collection>()
                .eq("post_id", id)
                .eq("type", 1));
        // 2.添加收藏数量
        int likes = collectionService.count(new QueryWrapper<Collection>()
                .eq("post_id", id)
                .eq("type", 2));
        map.put("code", 200);
        map.put("msg", "查询博客收藏点赞成功");
        map.put("collection", collection);
        map.put("likes", likes);
        return map;
    }

    /**
     * 用户是否点赞或收藏文章
     *
     * @param postId 文章ID
     * @param userId 请求的用户ID
     * @return 返回HashMap结果集, 其中包括请求用户是否点赞或收藏文章的json信息
     */
    @GetMapping("/getBlog/{postId}/{userId}")
    public Map<String, Object> getBlogByUser(
            @PathVariable(name = "postId") Long postId,
            @PathVariable(name = "userId") Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        // 1.查询个人是否收藏此文章
        Collection collection = collectionService.getOne(new QueryWrapper<Collection>()
                .eq("post_id", postId)
                .eq("user_id", userId)
                .eq("type", 1));
        if (collection != null)
            map.put("collection", true);
        else
            map.put("collection", false);
        // 2.查询个人是否点赞此文章
        Collection like = collectionService.getOne(new QueryWrapper<Collection>()
                .eq("post_id", postId)
                .eq("user_id", userId)
                .eq("type", 2));
        if (like != null)
            map.put("like", true);
        else
            map.put("like", false);
        map.put("code", 200);
        map.put("msg", "查询个人是否收藏点赞博客成功");
        return map;
    }
}
